import { nanoid } from 'nanoid';
import { WindowService } from './index';
import { __path } from '@e/methods/path';
import { readFile } from '@e/methods/file';
import { Resource } from '@p/WindowService';
import { getImageType } from '@e/methods/image';
import { matchExtRegex } from '@e/utils/regexp';
import { ImageInfo } from '@p/main-windowObject';
import { downloadFile } from '@e/methods/download';
import { ReplaceOption, ReplaceOptions } from '@type/replace';
import { bufferToBase64URL, extractFilenameFromURL } from '@e/methods/url';

/**
 * 生成图片资源
 */
export async function generateImageResource(
	this: WindowService,
	downloadImage = false,
	savePath: string,
	useBase64URL = false
) {
	const imageInfo = this.fileInfo?.imageInfo || [];
	const imageResources: Resource[] = [];
	const replaceList: ReplaceOptions = [];

	// 读取本地图片
	const readLocalImage = async (imageInfo: ImageInfo) => {
		if ((imageInfo.type === 'absolute' || imageInfo.type === 'relative') && imageInfo.fileExist) {
			const { err, data } = await readFile(imageInfo.absolute as string);

			if (err) {
				this.sendMessage('insert', 'error', `读取图片文件失败: ${imageInfo.absolute}`);
			} else {
				this.sendMessage('insert', 'success', `读取图片文件成功: ${imageInfo.filename}`);

				// 添加在图片资源
				imageResources.push({
					name: imageInfo.filename as string,
					type: 'file',
					data,
				});

				// 是否添加替换配置
				let addreplaceOption = true;
				const replaceOption: ReplaceOption = {
					target: imageInfo.target,
					substituted: '',
					directReplace: true,
				};

				// 使用 base64URL
				if (useBase64URL) {
					const base64URL = bufferToBase64URL(data);

					if (base64URL) {
						replaceOption.substituted = base64URL;
					} else {
						addreplaceOption = false;
					}
				} else {
					replaceOption.substituted = __path.relative_join(false, savePath, imageInfo.filename as string);
				}

				if (addreplaceOption) replaceList.push(replaceOption);
			}
		}
	};

	// 下载网络图片
	const innerDownloadImage = async (imageInfo: ImageInfo) => {
		if (downloadImage && imageInfo.type === 'url') {
			let filename = extractFilenameFromURL(imageInfo.target) || nanoid();
			let data: Buffer;

			const messageId = this.sendMessage('insert', 'info', `正在下载：${filename}`);

			// 查看缓存中是否有
			const cacheData = this.imageCacheData.get(imageInfo.target);

			if (cacheData) {
				data = cacheData.buffer;
			} else {
				try {
					// 下载
					data = await downloadFile(imageInfo.target, (progress) => {
						this.sendMessage('update', 'info', `正在下载：${filename} ${progress}%`, messageId);
					});
				} catch (error) {
					let msg = error instanceof Error ? error.message : '';
					// 出现错误
					this.sendMessage('update', 'error', `下载错误：${msg} \n 下载地址：${imageInfo.target}`, messageId);

					return;
				}
			}

			// 没有文件名的情况
			if (!matchExtRegex.test(filename)) {
				const imageTypeResult = getImageType(data);

				if (!imageTypeResult) {
					this.sendMessage(
						'update',
						'error',
						`不是图片${filename} \n 下载地址：${imageInfo.target}`,
						messageId
					);

					return;
				}

				filename += '.' + imageTypeResult.ext;
			}

			this.sendMessage('update', 'success', `图片下载成功: ${filename}`, messageId);

			imageResources.push({
				name: filename,
				type: 'file',
				data,
			});

			// 是否添加替换配置
			let addreplaceOption = true;
			const replaceOption: ReplaceOption = {
				target: imageInfo.target,
				substituted: '',
				directReplace: true,
			};

			// 使用 base64URL
			if (useBase64URL) {
				const base64URL = bufferToBase64URL(data);

				if (base64URL) {
					replaceOption.substituted = base64URL;
				} else {
					addreplaceOption = false;
				}
			} else {
				replaceOption.substituted = __path.relative_join(false, savePath, filename as string);
			}

			if (addreplaceOption) replaceList.push(replaceOption);
		}
	};

	for (let i = 0; i < imageInfo.length; i++) {
		const item = imageInfo[i];

		if (item.exist) continue;

		await readLocalImage(item);

		await innerDownloadImage(item);
	}

	return { imageResources, replaceList };
}
